﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;

namespace ProtocolConversion_WINCE
{
    public partial class BDForm : Form
    {

        #region 字段
        public SerialPort sp;
        public static string strPortName = "";
        public static string strBaudRate = "";
        public static string strDataBits = "";
        public static string strStopBits = "";
        public static bool IsSet = false;
        public static bool isStar = false;

        public Thread _readThread;
        public bool _keepReading;
        private Boolean isSerialPortOpen = false;
        //获取到主窗体
        private Form mainForm;

        public delegate void AppendStringDelegate(string str);
        public AppendStringDelegate appendstringdelegate; 
        #endregion

        public BDForm()
        {
            InitializeComponent();
        }

        public BDForm(Form mainForm)
        { 
            InitializeComponent();
            Init(mainForm);
        }

        private void Init(Form mainForm)
        {   //传递主窗体
            this.mainForm = mainForm;
            //初始化窗体位置
            Rectangle rect = Screen.PrimaryScreen.WorkingArea;
            int width, height;
            width = (rect.Width - this.Size.Width) / 2;
            height = (rect.Height - this.Size.Height) / 2;
            this.Location = new Point(width, height);
        }

        private void BDForm_Load(object sender, EventArgs e)
        {
            comboBox1.Items.Add("混发");//0
            comboBox1.Items.Add("代码");//1
            comboBox1.Items.Add("汉字");//2
            comboBox1.SelectedIndex = 0;


            string[] ports = SerialPort.GetPortNames();
            foreach (string port in ports)
            {
                cmbPort.Items.Add(port);
            }

            cmbPort.SelectedIndex = 0;
            cmbBaudRate.Items.Add("9600");
            cmbBaudRate.Items.Add("19200");
            cmbBaudRate.Items.Add("38400");
            cmbBaudRate.Items.Add("115200");
            cmbBaudRate.SelectedIndex = 3;
            cmbDataBits.Items.Add("8");
            cmbDataBits.SelectedIndex = 0;
            cmbStopBit.Items.Add("1");
            cmbStopBit.SelectedIndex = 0;
            cmbParity.Items.Add("无");
            cmbParity.SelectedIndex = 0;

            sp = new SerialPort();
            sp.ReadTimeout = 500;
            sp.WriteTimeout = 500;
            sp.ReadBufferSize = 1024;
            _readThread = new Thread(ReadPort);
            
            this.richTextBox1.WordWrap = false;

            appendstringdelegate = new AppendStringDelegate(AppendString);
        }
        //showMessage
        public void AppendString(string value)
        {

            if (richTextBox1.InvokeRequired)
            {
                AppendStringDelegate d = new AppendStringDelegate(AppendString);
                richTextBox1.Invoke(d, value);
            }
            else
            {
                richTextBox1.Select(richTextBox1.TextLength, 0);
                richTextBox1.ScrollToCaret();
                richTextBox1.WordWrap = true;
                richTextBox1.Text += value + Environment.NewLine;
               
            }
        }       
        //串口接收数据函数
        private void ReadPort()
        {
            byte[] readBuffer = new byte[300];
            int bytecount = 0; //
            byte tmp = 0;
            DateTime startTime = DateTime.Now;
            while (_keepReading)  //读状态
            {
                if (sp.IsOpen)    //串口打开
                {
                    try
                    {
                        try
                        {
                            tmp = (byte)sp.ReadByte();
                        }
                        catch { }

                        if (bytecount != 0)//计数不为0说明已经检测到$
                        {
                            if ((tmp == (byte)0x24 && bytecount > 10 && Datalen(readBuffer) == bytecount) || (tmp != (byte)0x24 && bytecount > 10 && Datalen(readBuffer) == bytecount))
                            {
                                string str = byteToHexStr(readBuffer, bytecount);
                                if (str.StartsWith("2449435858"))//$ICXX
                                {
                                    byte[] address = new byte[] { (byte)0, readBuffer[7], readBuffer[8], readBuffer[9] };
                                    byte[] tb = new byte[] { (byte)0, readBuffer[11], readBuffer[12], readBuffer[13] };
                                    byte[] freq = new byte[] { readBuffer[15], readBuffer[16] };
                                    byte[] level = new byte[] { (byte)0, readBuffer[17] };
                                    if (BitConverter.IsLittleEndian)
                                    {
                                        Array.Reverse(address);
                                        Array.Reverse(level);
                                        Array.Reverse(freq);
                                        Array.Reverse(tb);
                                    }
                                    int vaddr = BitConverter.ToInt32(address, 0); //                                                                            
                                    int vtb = BitConverter.ToInt32(tb, 0);
                                    Int16 vfreq = BitConverter.ToInt16(freq, 0);
                                    Int16 vlevel = BitConverter.ToInt16(level, 0);
                                    AppendString(DateTime.Now.ToString() + " IC信息:卡号" + vaddr + "  通播：" + vtb + "   频度：" + vfreq + "   等级:" + vlevel);
                                }
                                else if (str.StartsWith("24474C5A4B"))
                                {
                                    byte[] one = new byte[] { (byte)0, readBuffer[10] };
                                    byte[] two = new byte[] { (byte)0, readBuffer[11] };
                                    byte[] three = new byte[] { (byte)0, readBuffer[12] };
                                    byte[] four = new byte[] { (byte)0, readBuffer[13] };
                                    byte[] five = new byte[] { (byte)0, readBuffer[14] };
                                    byte[] six = new byte[] { (byte)0, readBuffer[15] };
                                    if (BitConverter.IsLittleEndian)
                                    {
                                        Array.Reverse(one);
                                        Array.Reverse(two);
                                        Array.Reverse(three);
                                        Array.Reverse(four);
                                        Array.Reverse(five);
                                        Array.Reverse(six);
                                    }
                                    Int16 onevalue = BitConverter.ToInt16(one, 0);
                                    Int16 twovalue = BitConverter.ToInt16(two, 0);
                                    Int16 threevalue = BitConverter.ToInt16(three, 0);
                                    Int16 fourvalue = BitConverter.ToInt16(four, 0);
                                    Int16 fivevalue = BitConverter.ToInt16(five, 0);
                                    Int16 sixvalue = BitConverter.ToInt16(six, 0);

                                    String signal = "功率状态:" + onevalue + "-" + twovalue + "-" + threevalue +
                                        "-" + fourvalue + "-" + fivevalue + "-" + sixvalue;

                                    AppendString(DateTime.Now.ToString() + " " + signal);
                                }
                                else if (str.StartsWith("2444575858"))
                                {//$DWXX
                                    byte[] useraddr = new byte[] { 0, readBuffer[7], readBuffer[8], readBuffer[9] };
                                    byte[] addr = new byte[] { 0, readBuffer[11], readBuffer[12], readBuffer[13] };
                                    byte[] h = new byte[] { (byte)0, readBuffer[14] };
                                    byte[] m = new byte[] { (byte)0, readBuffer[15] };
                                    byte[] s = new byte[] { (byte)0, readBuffer[16] };
                                    byte[] ss = new byte[] { (byte)0, readBuffer[17] };

                                    byte[] L = new byte[] { (byte)0, readBuffer[18] };
                                    byte[] LL = new byte[] { (byte)0, readBuffer[19] };
                                    byte[] LLL = new byte[] { (byte)0, readBuffer[20] };
                                    byte[] LLLL = new byte[] { (byte)0, readBuffer[21] };

                                    byte[] B = new byte[] { (byte)0, readBuffer[22] };
                                    byte[] BB = new byte[] { (byte)0, readBuffer[23] };
                                    byte[] BBB = new byte[] { (byte)0, readBuffer[24] };
                                    byte[] BBBB = new byte[] { (byte)0, readBuffer[25] };

                                    byte[] MS = new byte[] { (byte)0, readBuffer[26] };
                                    byte[] M = new byte[] { (byte)0, readBuffer[27] };

                                    byte[] HS = new byte[] { (byte)0, readBuffer[28] };
                                    byte[] H = new byte[] { (byte)0, readBuffer[29] };
                                    if (BitConverter.IsLittleEndian)
                                    {
                                        Array.Reverse(useraddr);
                                        Array.Reverse(addr);
                                        Array.Reverse(h);
                                        Array.Reverse(m);
                                        Array.Reverse(s);
                                        Array.Reverse(ss);
                                        Array.Reverse(L);
                                        Array.Reverse(LL);
                                        Array.Reverse(LLL);
                                        Array.Reverse(LLLL);
                                        Array.Reverse(B);
                                        Array.Reverse(BB);
                                        Array.Reverse(BBB);
                                        Array.Reverse(BBBB);
                                        Array.Reverse(MS);
                                        Array.Reverse(M);
                                        Array.Reverse(HS);
                                        Array.Reverse(H);
                                    }
                                    Int32 useraddress = BitConverter.ToInt32(useraddr, 0);
                                    Int32 address = BitConverter.ToInt32(addr, 0);
                                    Int16 hvalue = BitConverter.ToInt16(h, 0);
                                    Int16 mvalue = BitConverter.ToInt16(m, 0);
                                    Int16 svalue = BitConverter.ToInt16(s, 0);
                                    Int16 ssvalue = BitConverter.ToInt16(ss, 0);
                                    Int16 lvalue = BitConverter.ToInt16(L, 0);
                                    Int16 llvalue = BitConverter.ToInt16(LL, 0);
                                    Int16 lllvalue = BitConverter.ToInt16(LLL, 0);
                                    Int16 llllvalue = BitConverter.ToInt16(LLLL, 0);
                                    Int16 bvalue = BitConverter.ToInt16(B, 0);
                                    Int16 bbvalue = BitConverter.ToInt16(BB, 0);
                                    Int16 bbbvalue = BitConverter.ToInt16(BBB, 0);
                                    Int16 bbbbvalue = BitConverter.ToInt16(BBBB, 0);
                                    Int16 MSvalue = BitConverter.ToInt16(MS, 0);
                                    Int16 Mvalue = BitConverter.ToInt16(M, 0);
                                    Int16 hsvalue = BitConverter.ToInt16(HS, 0);
                                    Int16 Hvalue = BitConverter.ToInt16(H, 0);
                                    int GAODU = Mvalue;
                                    int gaoduyichang = Hvalue;

                                    if (hsvalue == 1)
                                    {
                                        gaoduyichang = gaoduyichang * (-1);
                                    }
                                    if (MSvalue == 1)
                                    {
                                        GAODU = GAODU * (-1);
                                    }

                                    String DingweiInfo = " " + hvalue + "时" + mvalue + "分" + svalue + "." + ssvalue + "秒" + " 用户地址 " + useraddress + " 查询地址 " + address +
                                                        " 经度 " + lvalue + "度" + llvalue + "分" + lllvalue + "." + llllvalue + "秒" +
                                                        " 纬度 " + bvalue + "度" + bbvalue + "分" + bbbvalue + "." + bbbbvalue + "秒" +
                                                        " 高度" + GAODU + "米" + " 高度异常" + gaoduyichang + "米";

                                    AppendString(DateTime.Now + DingweiInfo);
                                }
                                else if (str.StartsWith("24464B5858"))
                                {//$FKXX                                
                                    byte[] value = new byte[2] { 0x0, readBuffer[10] };
                                    if (BitConverter.IsLittleEndian)
                                    {
                                        Array.Reverse(value);
                                    }
                                    Int16 ret = BitConverter.ToInt16(value, 0);
                                    if (ret == 0)
                                    {
                                        byte[] byteArray = new byte[4] { readBuffer[11], readBuffer[12], readBuffer[13], readBuffer[14] };
                                        string data = byteToHexStr(byteArray, 4);
                                        if (data == "44575351")
                                        {
                                            AppendString(DateTime.Now + " 反馈信息：定位申请发送成功");
                                        }
                                        else if (data == "54585351")
                                        {
                                            AppendString(DateTime.Now + " 反馈信息：通信申请发送成功");
                                        }
                                        else
                                        {
                                            AppendString(DateTime.Now + " 反馈信息：发送成功");
                                        }
                                    }
                                    else if (ret == 1)
                                    {
                                        byte[] byteArray = new byte[4] { readBuffer[11], readBuffer[12], readBuffer[13], readBuffer[14] };
                                        string data = byteToHexStr(byteArray, 4);
                                        if (data == "44575351")
                                        {
                                            AppendString(DateTime.Now + " 反馈信息：定位申请发送失败");
                                        }
                                        else if (data == "54585351")
                                        {
                                            AppendString(DateTime.Now + "  反馈信息：通信申请发送失败");
                                        }

                                    }
                                    else if (ret == 2)
                                    {
                                        AppendString(DateTime.Now + " 反馈信息：信号未锁定");
                                    }
                                    else if (ret == 3)
                                    {
                                        AppendString(DateTime.Now + " 反馈信息：电量不足");
                                    }
                                    else if (ret == 4)
                                    {//超频
                                        //
                                        byte[] waittime = new byte[4] { readBuffer[11], readBuffer[12], readBuffer[13], readBuffer[14] };
                                        Int32 time = BitConverter.ToInt32(waittime, 0);
                                        AppendString(DateTime.Now + " 反馈信息：发射频度未到,再等待" + time + "秒！");

                                    }
                                    else if (ret == 5)
                                    {
                                        AppendString(DateTime.Now + " 反馈信息：加解密错误");
                                    }
                                    else if (ret == 6)
                                    {
                                        AppendString(DateTime.Now + " 反馈信息：CRC错误");
                                    }
                                }
                                else if (str.StartsWith("2454585858"))
                                {
                                    //通信信息TXXX
                                    byte xinxileibie = readBuffer[10];
                                    byte[] useraddr = new byte[] { 0, readBuffer[7], readBuffer[8], readBuffer[9] };
                                    byte[] remoteAddr = new byte[] { 0x0, readBuffer[11], readBuffer[12], readBuffer[13] };
                                    byte[] sendtimeh = new byte[] { 0x0, readBuffer[14] };
                                    byte[] sendtimem = new byte[] { 0x0, readBuffer[15] };
                                    byte[] contentBitlen = new byte[] { readBuffer[16], readBuffer[17] };
                                    byte fangshi = (byte)(xinxileibie & 0x60);
                                    if (BitConverter.IsLittleEndian)
                                    {
                                        Array.Reverse(useraddr);
                                        Array.Reverse(contentBitlen);
                                        Array.Reverse(remoteAddr);
                                        Array.Reverse(sendtimeh);
                                        Array.Reverse(sendtimem);
                                    }

                                    Int16 contentlenvalue = BitConverter.ToInt16(contentBitlen, 0);
                                    Int16 sendtimehvalue = BitConverter.ToInt16(sendtimeh, 0);
                                    Int16 sendtimemnvalue = BitConverter.ToInt16(sendtimem, 0);
                                    Int32 receiveraddr = BitConverter.ToInt32(useraddr, 0);
                                    Int32 remoteAddrvalue = BitConverter.ToInt32(remoteAddr, 0);
                                    int contentlen = contentlenvalue / 8;//
                                    byte[] content = new byte[contentlen]; //
                                    for (int i = 0; i < contentlen; i++)
                                    {
                                        content[i] = readBuffer[18 + i];
                                    }
                                    String duanxin = "";  //
                                    String baowenfanshi = "";
                                    if (fangshi == 0x60)  //
                                    {
                                        byte[] newconent = new byte[content.Length - 1];
                                        if (content[0] == 0xA4)
                                        {
                                            for (int i = 0; i < contentlen - 1; i++)
                                            {
                                                newconent[i] = content[1 + i];
                                            }
                                            string xinxi = System.Text.Encoding.Default.GetString(newconent,0,newconent .Length );
                                            duanxin = xinxi;
                                            baowenfanshi = "混发";
                                        }
                                        else
                                        {
                                            String hex = byteToHexStr(content, content.Length);
                                            baowenfanshi = "代码";
                                            duanxin = hex;
                                        }
                                    }
                                    else if (fangshi == 0x40)
                                    {
                                        string xinxi = System.Text.Encoding.Default.GetString(content,0,content .Length );
                                        baowenfanshi = "汉字";
                                        duanxin = xinxi;
                                    }
                                    AppendString(DateTime.Now + " " + receiveraddr + " 收到" + baowenfanshi + "报文: 来自" + remoteAddrvalue + " 时间：" + sendtimehvalue + "时" + sendtimemnvalue + "分 " + "内容：" + duanxin);

                                }
                                else
                                {
                                    //AppendString(DateTime.Now + " ：" + str);
                                }

                                if (tmp == (byte)0x24)
                                {
                                    readBuffer[0] = tmp;
                                    bytecount = 1;
                                }
                                else
                                {
                                    bytecount = 0;
                                }
                            }
                            else if (tmp == (byte)0x0A && readBuffer[bytecount - 1] == (byte)0x0D)//判断BD2/GPS数
                            {//RN
                                string gpsdata = System.Text.Encoding.Default.GetString(readBuffer,0,readBuffer.Length ).Trim(); //根据ASCII获取短报文内容                               
                                //if (BD2GPSCK.Checked)//是否显示二代数据
                                {
                                    //AppendString(gpsdata);
                                }
                                readBuffer = new byte[300];
                                bytecount = 0;
                            }
                            else
                            {
                                try
                                {
                                    readBuffer[bytecount++] = tmp;
                                }
                                catch
                                {
                                    bytecount = 0;
                                }
                            }
                        }
                        else
                        {
                            //计数还是为零的时候判断是是否检测到‘$’
                            if (tmp == (byte)0x24)
                            {
                                readBuffer[bytecount++] = tmp;
                            }
                        }
                    }
                    catch (TimeoutException) { }
                }
                else
                { //如果串口没打开
                    //TimeSpan waitTime = new TimeSpan(0, 0, 0, 0, 50);
                    int waitTime = 100;
                    Thread.Sleep(waitTime);
                }
            }
        }

        public static string byteToHexStr(byte[] bytes, int len)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < len; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }

        public int Datalen(byte[] buffer)
        {

            byte[] len = new byte[] { (byte)0, (byte)0, buffer[5], buffer[6] };
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(len);
            }
            int ret = BitConverter.ToInt32(len, 0);
            return ret;
        }
        //关闭
        private void button8_Click(object sender, EventArgs e)
        {
            if (isSerialPortOpen)
            {
                _keepReading = false;
                if (isStar)
                {
                    try
                    {
                        //_readThread.Suspend();
                        //_readThread.Abort();
                    }
                    catch { }
                }
                if (sp.IsOpen)
                {
                    sp.Close();
                    button1.Enabled = true;
                }
                button1.Text = "打开";
                isSerialPortOpen = false;
            }
        }
        //打开串口
        private void button1_Click(object sender, EventArgs e)
        {
            sp.PortName = cmbPort.Text;
            sp.BaudRate = int.Parse(cmbBaudRate.Text);
            sp.DataBits = int.Parse(cmbDataBits.Text);
            sp.StopBits = (StopBits)int.Parse(cmbStopBit.Text);
            sp.ReadTimeout = 500;

            if (cmbPort.Text != "")
            {
                IsSet = true;
            }
            else
            {
                return;
            }
            if (!isSerialPortOpen)
            {
                if (!IsSet)
                {
                    MessageBox.Show("请先设置串口");
                    return;
                }
                if (!sp.IsOpen)
                {
                    try
                    {
                        sp.Open();
                        isSerialPortOpen = true;
                        button1.Enabled = false;
                        //try
                        //{
                        //    _readThread.Start();
                        //}
                        //catch { }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("打开失败！" + ex.ToString());
                        button1.Enabled = true;
                        return;
                    }
                    button1.Text = "已连";
                }
                _keepReading = true;
                if (!isStar)
                {
                    _readThread.Start();
                    isStar = true;
                }
                else
                {
                    try
                    {
                        //weince 线程无法挂起，没有执行线程挂起的方法
                        //_readThread.Resume();
                        //_readThread.Start();
                       
                    }
                    catch { }
                }
            }
        }        
        //清空接收数据
        private void cleardatatbn_Click(object sender, EventArgs e)
        {
            this.richTextBox1.Text = "";
        }
        //IC检测
        private void button3_Click(object sender, EventArgs e)
        {
            if (!sp.IsOpen)
            {
                AppendString("串口未打开");
                return;
            }
            byte[] send = new byte[] { 0x24, 0x49, 0x43, 0x4A, 0x43, 0x00, 0x0C, 0x0, 0x0, 0x0, 0x1, 0x2A };
            try
            {
                sp.Write(send, 0, send.Length);
            }
            catch { }
            AppendString(DateTime.Now + " IC检测");
        }
        //功率检测
        private void button4_Click(object sender, EventArgs e)
        {
            if (!sp.IsOpen)
            {
                AppendString("串口未打开");
                return;
            }
            byte[] send = new byte[] { 0x24, 0x47, 0x4C, 0x4A, 0x43, 0x00, 0x0C, 0x0, 0x0, 0x0, 0x1, 0x2b };
            sp.Write(send, 0, send.Length);
            AppendString(DateTime.Now + " 功率检测");
        }
        //单次定位
        private void button5_Click(object sender, EventArgs e)
        {
            if (!sp.IsOpen)
            {
                AppendString("串口未打开");
                return;
            }
            byte[] cmddw = new byte[] { 0x24, 0x44, 0x57, 0x53, 0x51, 0x0, 0x16, 0x0, 0x0, 0x0, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x27 };
            sp.Write(cmddw, 0, cmddw.Length);
            AppendString(DateTime.Now + " 单次定位");
        }
        //单次通信
        private void button6_Click(object sender, EventArgs e)
        {
            sendbdbaowen();
        }
        //清空发送数据
        private void button16_Click(object sender, EventArgs e)
        {
            this.textBox2.Text = "";
        }
        //显示主界面
        private void button9_Click(object sender, EventArgs e)
        {
            mainForm.Show();
            this.Hide();
        }
        //单次通信——sendbdbaowen
        public void sendbdbaowen()
        {
            if (!sp.IsOpen)
            {
                AppendString("串口未打开");
                return;
            }
            String ID = textBox1.Text;
            Int32 addr = 0;
            if (ID != "" && ID != null)
            {
                addr = System.Int32.Parse(ID);
            }
            else
            {
                MessageBox.Show("未输入接收方卡号");
                return;
            }
            byte[] addrbytes = System.BitConverter.GetBytes(addr);
            byte l = addrbytes[0];
            byte m = addrbytes[1];
            byte h = addrbytes[2];
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(addrbytes);
            }

            String sms = textBox2.Text;
            byte[] smsbytes;
            Int32 contentLen = 0;
            int fangshi = comboBox1.SelectedIndex;
            byte[] xinxileibie = new byte[1];
            if (fangshi == 2)
            {
                xinxileibie[0] = 0x44;//汉字
                smsbytes = System.Text.Encoding.Default.GetBytes(sms);
                contentLen = smsbytes.Length;
            }
            else if (fangshi == 0)
            {
                xinxileibie[0] = 0x46; //混发
                smsbytes = System.Text.Encoding.Default.GetBytes(sms);
                contentLen = smsbytes.Length;
            }
            else
            { //选择代码发送
                xinxileibie[0] = 0x46; //代码
                //以下处理仅是测试软件为了方便测试看到效果做的处理，实际协议应用不需要怎么处理
                byte[] data = System.Text.Encoding.Default.GetBytes(sms);
                if (data.Length > 0)
                {
                    if (data.Length % 2 == 0)
                    {
                        smsbytes = new byte[data.Length / 2];
                        for (int i = 0, j = 0; i < data.Length; i += 2, j++)
                        {
                            byte a = (byte)((data[i] - 0x30) & 0x0f);//取偶数 0011 0000   00001111
                            byte b = (byte)((data[i + 1] - 0x30) & 0x0f);//取奇数
                            smsbytes[j] = (byte)(a << 4 | b);
                        }
                        contentLen = smsbytes.Length;
                    }
                    else
                    {
                        smsbytes = new byte[data.Length / 2 + 1];
                        for (int i = 0, j = 0; i < data.Length - 1; i += 2, j++)
                        {
                            byte a = (byte)((data[i] - 0x30) & 0x0f);
                            byte b = (byte)((data[i + 1] - 0x30) & 0x0f);
                            smsbytes[j] = (byte)(a << 4 | b);
                        }
                        AppendString("代码方式奇数位末尾补F");
                        smsbytes[data.Length / 2] = (byte)(((data[data.Length - 1] - 0x30) & 0x0f) << 4 | 0x0f);
                        contentLen = smsbytes.Length;
                    }
                }
                else
                {
                    smsbytes = new byte[0];
                }
            }
            Int32 contentLenbit = contentLen * 8;//电文内容长度(比特数)
            if (fangshi == 0)
            { //混发
                contentLen += 1;
                contentLenbit += 8; //多了一个0xA4  比特数加8
            }
            if (contentLenbit > 1680)
            {
                MessageBox.Show("输入内容长度为" + contentLenbit + "bit大于允许最大长度1680bit");
                return;
            }
            Int32 len = contentLen + 18;
            byte[] cmdtxsq = new byte[len];
            cmdtxsq[0] = 0x24;
            cmdtxsq[1] = 0x54;
            cmdtxsq[2] = 0x58;
            cmdtxsq[3] = 0x53;
            cmdtxsq[4] = 0x51;
            cmdtxsq[5] = (byte)(len >> 8 & 0x000000FF);
            cmdtxsq[6] = (byte)(len & 0x000000FF);
            cmdtxsq[7] = 0x0;
            cmdtxsq[8] = 0x0;
            cmdtxsq[9] = 0x0;
            cmdtxsq[10] = xinxileibie[0];
            cmdtxsq[11] = addrbytes[1];
            cmdtxsq[12] = addrbytes[2];
            cmdtxsq[13] = addrbytes[3];
            cmdtxsq[14] = (byte)(contentLenbit >> 8 & 0x000000ff);
            cmdtxsq[15] = (byte)(contentLenbit & 0x000000ff);
            cmdtxsq[16] = 0x0;

            if (fangshi == 0)
            {
                cmdtxsq[17] = 0xA4;
                for (int i = 0; i < smsbytes.Length; i++)
                {
                    cmdtxsq[18 + i] = smsbytes[i];
                }
            }

            else
            {
                for (int i = 0; i < smsbytes.Length; i++)
                {
                    cmdtxsq[17 + i] = smsbytes[i];
                }
            }
            cmdtxsq[len - 1] = bd_get_checksum(cmdtxsq, len - 1);

            sp.Write(cmdtxsq, 0, cmdtxsq.Length);

            AppendString(DateTime.Now + " 通信申请 发往:" + textBox1.Text + " 内容:" + textBox2.Text);
        }

        public void sendbdbaowenTest(byte[] sendDate)
        {
            if (!sp.IsOpen)
            {
                AppendString("串口未打开");
                return;
            }
            String ID = textBox1.Text;
            Int32 addr = 0;
            if (ID != "" && ID != null)
            {
                addr = System.Int32.Parse(ID);
            }
            else
            {
                MessageBox.Show("未输入接收方卡号");
                return;
            }
            byte[] addrbytes = System.BitConverter.GetBytes(addr);
            byte l = addrbytes[0];
            byte m = addrbytes[1];
            byte h = addrbytes[2];
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(addrbytes);
            }

            String sms = textBox2.Text;
            byte[] smsbytes;
            Int32 contentLen = 0;
            int fangshi = comboBox1.SelectedIndex;
            byte[] xinxileibie = new byte[1];
            if (fangshi == 2)
            {
                xinxileibie[0] = 0x44;//汉字
                //smsbytes = System.Text.Encoding.Default.GetBytes(sms);
                smsbytes = sendDate;
                contentLen = smsbytes.Length;
            }
            else if (fangshi == 0)
            {
                xinxileibie[0] = 0x46; //混发
                //smsbytes = System.Text.Encoding.Default.GetBytes(sms);
                smsbytes = sendDate;
                contentLen = smsbytes.Length;
            }
            else
            { //选择代码发送
                xinxileibie[0] = 0x46; //代码
                //以下处理仅是测试软件为了方便测试看到效果做的处理，实际协议应用不需要怎么处理
                //byte[] data = System.Text.Encoding.Default.GetBytes(sms);
                byte[] data = sendDate;
                if (data.Length > 0)
                {
                    if (data.Length % 2 == 0)
                    {
                        smsbytes = new byte[data.Length / 2];
                        for (int i = 0, j = 0; i < data.Length; i += 2, j++)
                        {
                            byte a = (byte)((data[i] - 0x30) & 0x0f);
                            byte b = (byte)((data[i + 1] - 0x30) & 0x0f);
                            smsbytes[j] = (byte)(a << 4 | b);
                        }
                        contentLen = smsbytes.Length;
                    }
                    else
                    {
                        smsbytes = new byte[data.Length / 2 + 1];
                        for (int i = 0, j = 0; i < data.Length - 1; i += 2, j++)
                        {
                            byte a = (byte)((data[i] - 0x30) & 0x0f);
                            byte b = (byte)((data[i + 1] - 0x30) & 0x0f);
                            smsbytes[j] = (byte)(a << 4 | b);
                        }
                        AppendString("代码方式奇数位末尾补F");
                        smsbytes[data.Length / 2] = (byte)(((data[data.Length - 1] - 0x30) & 0x0f) << 4 | 0x0f);
                        contentLen = smsbytes.Length;
                    }
                }
                else
                {
                    smsbytes = new byte[0];
                }
            }
            Int32 contentLenbit = contentLen * 8;//电文内容长度(比特数)
            if (fangshi == 0)
            { //混发
                contentLen += 1;
                contentLenbit += 8; //多了一个0xA4  比特数加8
            }
            if (contentLenbit > 1680)
            {
                MessageBox.Show("输入内容长度为" + contentLenbit + "bit大于允许最大长度1680bit");
                return;
            }
            Int32 len = contentLen + 18;
            byte[] cmdtxsq = new byte[len];
            cmdtxsq[0] = 0x24;
            cmdtxsq[1] = 0x54;
            cmdtxsq[2] = 0x58;
            cmdtxsq[3] = 0x53;
            cmdtxsq[4] = 0x51;
            cmdtxsq[5] = (byte)(len >> 8 & 0x000000FF);
            cmdtxsq[6] = (byte)(len & 0x000000FF);
            cmdtxsq[7] = 0x0;
            cmdtxsq[8] = 0x0;
            cmdtxsq[9] = 0x0;
            cmdtxsq[10] = xinxileibie[0];
            cmdtxsq[11] = addrbytes[1];
            cmdtxsq[12] = addrbytes[2];
            cmdtxsq[13] = addrbytes[3];
            cmdtxsq[14] = (byte)(contentLenbit >> 8 & 0x000000ff);
            cmdtxsq[15] = (byte)(contentLenbit & 0x000000ff);
            cmdtxsq[16] = 0x0;

            if (fangshi == 0)
            {
                cmdtxsq[17] = 0xA4;
                for (int i = 0; i < smsbytes.Length; i++)
                {
                    cmdtxsq[18 + i] = smsbytes[i];
                }
            }

            else
            {
                for (int i = 0; i < smsbytes.Length; i++)
                {
                    cmdtxsq[17 + i] = smsbytes[i];
                }
            }
            cmdtxsq[len - 1] = bd_get_checksum(cmdtxsq, len - 1);

            sp.Write(cmdtxsq, 0, cmdtxsq.Length);

            AppendString(DateTime.Now + " 通信申请 发往:" + textBox1.Text + " 内容:" + textBox2.Text);
        }

        byte bd_get_checksum(byte[] bytes, int slen)
        {
            byte ch = 0;
            int i = 0;
            for (i = 0; i < slen; i++)
            {
                byte h;
                h = bytes[i];
                ch ^= h;
            }
            return ch;
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                int kc = (int)e.KeyChar;
                if ((kc < 48 || kc > 57) && kc != 8)
                    e.Handled = true;
            }
            catch (Exception) { }
        }
        //关闭并释放占用的资源
        protected override void OnClosing(CancelEventArgs e)
        {
            DialogResult result = MessageBox.Show("关闭后将无法使用北斗,你确定要关闭此窗口？", "退出", 
                MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
            if (result == DialogResult.OK)
            {
                mainForm.Show();//先显示主窗体
                base.OnClosed(e);
                if (isSerialPortOpen)
                    sp.Close();
                this.Dispose();                
            }
            else
            {
                e.Cancel = true;
            }
        }
    }
}